其他
聊点基础的--sizeof,strlen,数组,字符串在一起能整哪些坑?
例子
#include <stdio.h>
#include <string.h>
void testArr(const char str[])
{
printf("%lu %lu\n", sizeof(str), strlen(str));
}
int main(void)
{
/*test 0*/
char str[] = "hello";
printf("test0 %lu %lu\n\n", sizeof(str), strlen(str)); //6 5
/*test 1*/
char str1[8] = "hello";
printf("test1 %lu %lu\n\n", sizeof(str1), strlen(str1)); //8 5
/**test 2*/
char str2[] = {'h','e','l','l','o'};
printf("test2 %lu %lu\n\n", sizeof(str2), strlen(str2)); //5 10
/**test 3*/
char *str3 = "hello";
printf("test3 %lu %lu\n\n", sizeof(str3), strlen(str3)); //8 5
/*test 4*/
char str4[] = "hello";
testArr(str4);//8 5
/*test 5*/
char str5[] = "hell\0o";
printf("test5 %lu %lu\n", sizeof(str5), strlen(str5)); //7 4
/*test 6*/
char str6[10] = {0};
printf("test6 %lu %lu\n\n", sizeof(str6), strlen(str6)); //10 0
/*test 7*/
char str7[5] = "hello";
printf("test7 %lu %lu\n\n", sizeof(str7), strlen(str7)); //5 10
/*test 8*/
char str8[5] = {0};
strncpy(str8,"hello",5);
printf("%s\n",str8);//hellohello
return 0;
}
在解释这些测试之前,先复习一下sizeof,strlen以及数组的内容。
sizeof
例如:
{
int a;
char b;
};
sizeof(int);//得到4
sizeof(test);//4字节对齐时,得到8
另外sizeof的时间复杂度是O(1)。
strlen
从参数s所指向的内存开始往后计数,直到内存中的内容是0(即’\0’,参考《NULL,0,'\0',“0”,"\0"你真的分得清吗?》)为止。
例如:
#include<string.h>
int main()
{
char *p = "hello";
printf("%lu\n",strlen(p));//得到5
return 0;
}
注:strlen的时间复杂度为O(N)。
数组
字符串
解析
test0
printf("test0 %lu %lu\n\n", sizeof(str), strlen(str)); //6 5
test1
char str1[8] = "hello";
printf("test1 %lu %lu\n\n", sizeof(str1), strlen(str1)); //8 5
test2
char str2[] = {'h','e','l','l','o'};
printf("test2 %lu %lu\n\n", sizeof(str2), strlen(str2)); //5 10
test3
char *str3 = "hello";//最后有一个”隐形“的'\0'
printf("test3 %lu %lu\n\n", sizeof(str3), strlen(str3)); //8 5
test4
char str4[] = "hello";
testArr(str4);//8 5
test5
char str5[] = "hell\0o";
printf("test5 %lu %lu\n", sizeof(str5), strlen(str5)); //7 4
test6
char str6[10] = {0};
printf("test6 %lu %lu\n\n", sizeof(str6), strlen(str6)); //10 0
test7
char str7[5] = "hello";
printf("test7 %lu %lu\n\n", sizeof(str7), strlen(str7)); //5 10
test8
char str8[5] = {0};
strncpy(str8,"hello",5);
printf("%s\n",str8);//hellohello
总结
sizeof计算类型占用空间大小,时间复杂度O(1) sizeof计算大小时会考虑字节对齐 strlen计算字符串长度,时间复杂度O(N) strlen作用对象是字符串(以'\0'结尾) strlen遇到'\0'作罢,如果没有遇到,则不可预料 格外小心数组作为参数
char *str2 = "hello";//存储在数据区,只读
相关精彩推荐